package com.chalmers.foa.gamemodel.gameobjects.switches.impl;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

import android.graphics.Bitmap;
import android.graphics.Point;

import com.chalmers.foa.gamehandlers.impl.CollisionHandler;
import com.chalmers.foa.gamemodel.events.IEvent;
import com.chalmers.foa.gamemodel.gameobjects.GameObjectBitmapAdapter;
import com.chalmers.foa.gamemodel.gameobjects.IGameObject;
import com.chalmers.foa.gamemodel.gameobjects.obstacles.IMovableObstacle;
import com.chalmers.foa.gamemodel.gameobjects.other.impl.PlayerObject;
import com.chalmers.foa.gamemodel.gameobjects.switches.ISwitch;
import com.chalmers.foa.util.NewList;

public class PushSwitch extends GameObjectBitmapAdapter implements ISwitch {

	private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
	private IEvent event;
	private NewList collidingObjects;
	private IGameObject otherObject;
	
	private boolean switched,doSwitch;
	
	public PushSwitch(Point position, Bitmap deactivated,int layer,int bound) {
		super(deactivated, position,layer,bound);
		collidingObjects = new NewList(10);
		doSwitch=false;
		switched=false;
	}
	
	public PushSwitch(Bitmap deactivated) {
		this( new Point(0,0),deactivated,0,-1);
	}
	
	public void update() {
		doSwitch = false;
		CollisionHandler.getInstance().objectsCollidingWithObject(this, 
				new Point(0,0), collidingObjects);
		for(int i = 0; i < collidingObjects.getSize(); i++) {
			otherObject = collidingObjects.getObjectAt(i);
			if((otherObject instanceof PlayerObject)||(otherObject instanceof IMovableObstacle)) {
				doSwitch = true;
				break;
			}
		}
		
		if(doSwitch) {
			if(!isSwitched()) {
				setSwitched();
			}
		}
		else {
			if(isSwitched()) {
				setSwitched();
			}
		}
	}
	@Override
	public void revertToStartPosition(){
		super.revertToStartPosition();
		doSwitch=false;
		switched=false;
	}
	public boolean isSwitched() {
		return switched;
	}
	
	public void setSwitched() {
		triggerEvent();
		revert();
	}
	public void revert(){
		switched=!switched;
	}

	@Override
	public void addPropertyChangeListener(PropertyChangeListener pcl) {
		pcs.addPropertyChangeListener(pcl);
	}

	@Override
	public void bindEvent(IEvent _event) {
		event=_event;
	}

	@Override
	public void triggerEvent() {
		pcs.firePropertyChange(new PropertyChangeEvent(this, "event", null, event));
	}

	@Override
	public boolean hasEvent() {
		return event!=null;
	}
}
